
import os
import sys
import subprocess
import time

def monitor_process(key_word, cmd):
    p1 = subprocess.Popen(['ps', '-e'], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['grep', key_word], stdin=p1.stdout, stdout=subprocess.PIPE)
    p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE)

    lines = p3.stdout.readlines()
    if len(lines) > 0:
        return

    sys.stderr.write('process[%s] is lost, run [%s]\n' % (key_word, cmd))
    subprocess.call(cmd, shell=True)

def main():
    while True:
        pidstr = ""
        try:
            fp = open("spiderkit.pid", "r")
            pidstr = fp.read()
            pidstr = pidstr.replace("\n","").replace("\r","").replace(" ", "")
            print pidstr
            fp.close()
        except:
            break

        monitor_process(pidstr, "./spiderkit-run.sh")
        time.sleep(5)

main()
